"""
分组管理路由
处理用户分组的创建、管理、权限控制和成员管理
"""

from typing import Annotated, List, Optional
import uuid
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session as DBSession

from src.config.database import get_db
from src.models.group import (
    GroupCreate, GroupUpdate, GroupResponse, UserGroupCreate, 
    GroupPermissionCreate, GroupFilter, UserGroupResponse, GroupPermissionResponse,
    GroupRole, GroupType
)
from src.services.auth_service import get_current_active_user_dep, require_admin
from src.services.group_service import GroupService
from src.models.user import User
from src.utils.logging import get_logger

logger = get_logger(__name__)

router = APIRouter(prefix="/groups", tags=["groups"])


@router.post("/", response_model=GroupResponse)
async def create_group(
    group_data: GroupCreate,
    db: Annotated[DBSession, Depends(get_db)],
    current_user: User = Depends(get_current_active_user_dep)
):
    """创建新分组"""
    try:
        # 显式转换 current_user.id 为 UUID 类型以解决类型检查错误
        created_by_uuid = uuid.UUID(str(current_user.id))
        group = GroupService.create_group(db, group_data, created_by_uuid)
        return GroupService.to_group_response(db, group)
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"创建分组失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="创建分组失败"
        )


@router.get("/", response_model=List[GroupResponse])
async def list_groups(
    db: Annotated[DBSession, Depends(get_db)],
    current_user: User = Depends(get_current_active_user_dep),
    name: Optional[str] = None,
    type: Optional[str] = None,
    parent_id: Optional[uuid.UUID] = None,
    is_active: Optional[bool] = None,
    user_id: Optional[uuid.UUID] = None,
):
    """获取分组列表"""
    try:
        filters = GroupFilter(
            name=name,
            type=[GroupType(type)] if type else None,
            parent_id=parent_id,
            is_active=is_active,
            user_id=user_id
        )
        groups = GroupService.list_groups(db, filters)
        return [GroupService.to_group_response(db, group) for group in groups]
    except Exception as e:
        logger.error(f"获取分组列表失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="获取分组列表失败"
        )


@router.get("/{group_id}", response_model=GroupResponse)
async def get_group(
    group_id: uuid.UUID,
    db: Annotated[DBSession, Depends(get_db)],
    current_user: User = Depends(get_current_active_user_dep)
):
    """获取分组详情"""
    try:
        group = GroupService.get_group(db, group_id)
        return GroupService.to_group_response(db, group)
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"获取分组详情失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="获取分组详情失败"
        )


@router.put("/{group_id}", response_model=GroupResponse)
async def update_group(
    group_id: uuid.UUID,
    group_data: GroupUpdate,
    db: Annotated[DBSession, Depends(get_db)],
    current_user: User = Depends(get_current_active_user_dep)
):
    """更新分组信息"""
    try:
        group = GroupService.update_group(db, group_id, group_data)
        return GroupService.to_group_response(db, group)
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"更新分组失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="更新分组失败"
        )


@router.delete("/{group_id}")
async def delete_group(
    group_id: uuid.UUID,
    db: Annotated[DBSession, Depends(get_db)],
    current_user: User = Depends(require_admin)
):
    """删除分组（仅管理员）"""
    try:
        GroupService.delete_group(db, group_id)
        return {"message": "分组删除成功"}
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"删除分组失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="删除分组失败"
        )


@router.post("/{group_id}/members", response_model=UserGroupResponse)
async def add_group_member(
    group_id: uuid.UUID,
    user_data: UserGroupCreate,
    db: Annotated[DBSession, Depends(get_db)],
    current_user: User = Depends(get_current_active_user_dep)
):
    """添加用户到分组"""
    try:
        user_group = GroupService.add_user_to_group(db, group_id, user_data)
        return GroupService.to_user_group_response(db, user_group)
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"添加用户到分组失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="添加用户到分组失败"
        )


@router.get("/{group_id}/members", response_model=List[UserGroupResponse])
async def get_group_members(
    group_id: uuid.UUID,
    db: Annotated[DBSession, Depends(get_db)],
    current_user: User = Depends(get_current_active_user_dep)
):
    """获取分组的所有成员"""
    try:
        members = GroupService.get_group_members(db, group_id)
        return [GroupService.to_user_group_response(db, member) for member in members]
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"获取分组成员失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="获取分组成员失败"
        )


@router.delete("/{group_id}/members/{user_id}")
async def remove_group_member(
    group_id: uuid.UUID,
    user_id: uuid.UUID,
    db: Annotated[DBSession, Depends(get_db)],
    current_user: User = Depends(get_current_active_user_dep)
):
    """从分组中移除用户"""
    try:
        GroupService.remove_user_from_group(db, group_id, user_id)
        return {"message": "用户已从分组中移除"}
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"从分组中移除用户失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="从分组中移除用户失败"
        )


@router.put("/{group_id}/members/{user_id}/role")
async def update_member_role(
    group_id: uuid.UUID,
    user_id: uuid.UUID,
    role: str,
    db: Annotated[DBSession, Depends(get_db)],
    current_user: User = Depends(get_current_active_user_dep)
):
    """更新用户在分组中的角色"""
    try:
        # 将字符串角色转换为GroupRole枚举
        group_role = GroupRole(role)
        user_group = GroupService.update_user_role(db, group_id, user_id, group_role)
        return {
            "message": "用户角色更新成功",
            "user_group": GroupService.to_user_group_response(db, user_group)
        }
    except ValueError:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=f"无效的角色: {role}。有效角色: {[r.value for r in GroupRole]}"
        )
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"更新用户角色失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="更新用户角色失败"
        )


@router.get("/user/{user_id}/groups", response_model=List[UserGroupResponse])
async def get_user_groups(
    user_id: uuid.UUID,
    db: Annotated[DBSession, Depends(get_db)],
    current_user: User = Depends(get_current_active_user_dep)
):
    """获取用户所属的所有分组"""
    try:
        user_groups = GroupService.get_user_groups(db, user_id)
        return [GroupService.to_user_group_response(db, ug) for ug in user_groups]
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"获取用户分组失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="获取用户分组失败"
        )


@router.post("/{group_id}/permissions", response_model=GroupPermissionResponse)
async def add_group_permission(
    group_id: uuid.UUID,
    permission_data: GroupPermissionCreate,
    db: Annotated[DBSession, Depends(get_db)],
    current_user: User = Depends(require_admin)
):
    """添加分组权限（仅管理员）"""
    try:
        permission = GroupService.add_group_permission(db, group_id, permission_data)
        return GroupPermissionResponse.from_orm(permission)
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"添加分组权限失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="添加分组权限失败"
        )


@router.get("/{group_id}/permissions", response_model=List[GroupPermissionResponse])
async def get_group_permissions(
    group_id: uuid.UUID,
    db: Annotated[DBSession, Depends(get_db)],
    current_user: User = Depends(get_current_active_user_dep)
):
    """获取分组的所有权限"""
    try:
        permissions = GroupService.get_group_permissions(db, group_id)
        return [GroupPermissionResponse.from_orm(perm) for perm in permissions]
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"获取分组权限失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="获取分组权限失败"
        )


@router.delete("/permissions/{permission_id}")
async def remove_group_permission(
    permission_id: uuid.UUID,
    db: Annotated[DBSession, Depends(get_db)],
    current_user: User = Depends(require_admin)
):
    """移除分组权限（仅管理员）"""
    try:
        GroupService.remove_group_permission(db, permission_id)
        return {"message": "分组权限已移除"}
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"移除分组权限失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="移除分组权限失败"
        )


@router.get("/{group_id}/hierarchy")
async def get_group_hierarchy(
    group_id: uuid.UUID,
    db: Annotated[DBSession, Depends(get_db)],
    current_user: User = Depends(get_current_active_user_dep)
):
    """获取分组的层级结构"""
    try:
        hierarchy = GroupService.get_group_hierarchy(db, group_id)
        return hierarchy
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"获取分组层级结构失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="获取分组层级结构失败"
        )


@router.get("/{group_id}/member-count")
async def get_group_member_count(
    group_id: uuid.UUID,
    db: Annotated[DBSession, Depends(get_db)],
    current_user: User = Depends(get_current_active_user_dep)
):
    """获取分组的成员数量"""
    try:
        count = GroupService.get_group_member_count(db, group_id)
        return {"member_count": count}
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"获取分组成员数量失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="获取分组成员数量失败"
        )
